import flet as ft
from dataclasses import dataclass
import json


# 数据结构
@dataclass
class Card:
	id: int
	title: str
	description: str
	list_id: int


@dataclass
class List:
	id: int
	title: str
	cards: list


class Board:
	def __init__(self):
		self.lists = []
		self.current_id = 1
	
	def add_list(self, title):
		new_list = List(self.current_id, title, [])
		self.lists.append(new_list)
		self.current_id += 1
		return new_list
	
	def find_card(self, card_id):
		for list in self.lists:
			for card in list.cards:
				if card.id == card_id:
					return card, list
		return None, None


# 主函数
def main(page: ft.Page):
	# 初始化看板
	board = Board()
	board.add_list(" 待办事项")
	board.add_list(" 进行中")
	board.add_list(" 已完成")
	
	# 添加示例卡片
	todo_list = board.lists[0]
	todo_list.cards.append(Card(1, "学习Flet", "完成Trello克隆项目", todo_list.id))
	
	# 保存/加载数据
	def save_data():
		data = {
			"lists": [
				{
					"id": l.id,
					"title": l.title,
					"cards": [
						{"id": c.id, "title": c.title,
						 "description": c.description, "list_id": c.list_id}
						for c in l.cards
					]
				}
				for l in board.lists
			],
			"current_id": board.current_id
		}
		with open("data.json", "w") as f:
			json.dump(data, f)
	
	def load_data():
		try:
			with open("data.json") as f:
				data = json.load(f)
				board.lists = [
					List(
						id=l["id"],
						title=l["title"],
						cards=[
							Card(
								id=c["id"],
								title=c["title"],
								description=c["description"],
								list_id=c["list_id"]
							) for c in l["cards"]
						]
					) for l in data["lists"]
				]
				board.current_id = data["current_id"]
		except FileNotFoundError:
			pass
	
	load_data()
	
	# 卡片编辑对话框
	# def show_edit_dialog(card: Card):
	# 	title_field.value = card.title
	# 	desc_field.value = card.description
	#
	# 	def save_changes(e):
	# 		card.title = title_field.value
	# 		card.description = desc_field.value
	# 		save_data()
	# 		page.update()
	# 		edit_dialog.open = False
	# 		page.update()
	#
	# 	edit_dialog.content = ft.Column([
	# 		ft.TextField(label="标题", value=card.title, id="title_field"),
	# 		ft.TextField(label="描述", value=card.description, id="desc_field", multiline=True)
	# 	])
	# 	edit_dialog.actions = [
	# 		ft.TextButton("保存", on_click=save_changes),
	# 		ft.TextButton("取消", on_click=lambda e: setattr(edit_dialog, "open", False))
	# 	]
	# 	page.dialog = edit_dialog
	# 	edit_dialog.open = True
	# 	page.update()
	
	# UI组件
	edit_dialog = ft.AlertDialog(
		title=ft.Text("编辑卡片"),
		modal=True
	)
	
	# 创建新列表
	new_list_title = ft.TextField(label="新列表标题")
	
	def add_new_list(e):
		title = new_list_title.value
		if title:
			board.add_list(title)
			save_data()
			page.update()
			new_list_dialog.open = False
			new_list_title.value = ""
			page.update()
	
	new_list_dialog = ft.AlertDialog(
		title=ft.Text("新建列表"),
		content=new_list_title,
		actions=[
			ft.TextButton("创建", on_click=add_new_list),
			ft.TextButton("取消", on_click=lambda e: setattr(new_list_dialog, "open", False))
		]
	)
	
	# 构建界面
	def build_board():
		return ft.Row(
			scroll=ft.ScrollMode.AUTO,
			spacing=20,
			controls=[
				         ft.DragTarget(
					         group="list",
					         content=ft.Container(
						         width=300,
						         padding=10,
						         bgcolor=ft.colors.BLUE_GREY_100,
						         border_radius=10,
						         content=ft.Column([
							         ft.Row([
								         ft.Text(list.title, size=18, weight="bold"),
								         ft.PopupMenuButton(
									         items=[
										         ft.PopupMenuItem(
											         text="删除列表",
											         on_click=lambda e: delete_list(list)
										         )
									         ]
								         )
							         ]),
							         ft.Divider(),
							         ft.Column(
								         spacing=10,
								         controls=[
									         ft.DragTarget(
										         group="cards",
										         on_accept=lambda e: handle_card_drop(e, list),
										         content=ft.Column(
											         spacing=10,
											         controls=[
												         ft.Draggable(
													         group="cards",
													         content=build_card(card),
													         data=card.id
												         ) for card in list.cards
											         ]
										         )
									         ),
									         ft.TextButton(
										         "添加卡片",
										         on_click=lambda e: add_card(list)
									         )
								         ]
							         )
						         ])
					         )
				         ) for list in board.lists
			         ] + [
				         ft.Container(
					         content=ft.TextButton(
						         "添加列表",
						         icon=ft.icons.ADD,
						         on_click=lambda e: setattr(new_list_dialog, "open", True)
					         ),
					         padding=10
				         )
			         ]
		)
	
	# 交互函数
	def add_card(target_list: List):
		new_card = Card(board.current_id, "新卡片")
		board.current_id += 1
		target_list.cards.append(new_card)
		save_data()
		page.update()
	
	def delete_list(target_list: List):
		board.lists.remove(target_list)
		save_data()
		page.update()
	
	def handle_card_drop(e, target_list: List):
		card_id = int(e.data)
		card, src_list = board.find_card(card_id)
		if card and src_list:
			src_list.cards.remove(card)
			card.list_id = target_list.id
			target_list.cards.append(card)
			save_data()
			page.update()
	
	# 构建卡片组件
	
	def build_card(card: Card):
		return ft.Card(
			elevation=3,
			content=ft.Container(
				content=ft.ListTile(
					title=ft.Text(card.title),
					subtitle=ft.Text(card.description, max_lines=2),
					# on_click=lambda e: show_edit_dialog(card)
				),
				width=280,
				padding=5,
				border_radius=5,
				bgcolor=ft.colors.WHITE
			)
		)
	
	# 页面布局
	page.title = "Trello 克隆"
	page.add(
		ft.AppBar(title=ft.Text("Trello 克隆"), bgcolor=ft.colors.BLUE_700),
		build_board()
	)
	page.dialog = new_list_dialog
	page.dialog = edit_dialog


if __name__ == "__main__":
	ft.app(target=main)